import ClickableObject from "./ClickableObject";
import Utils from "./utils";
import AnimatedNode from "./amn/AnimatedNode";
import SingleFlameSelector from "./frameselector";
import GameConst from "./GameConst";
import SoundsManager from "./soundmanager";

export default class ButtonObject extends ClickableObject {
    constructor(t, callback, parent, x, y) {
        super(t);
        if (typeof x === "undefined") {
            x = 0;
        }
        if (typeof y === "undefined") {
            y = 0;
        }

        this.playAnimIn = -1;
        this.callback = callback;
        var amn = this.getButtonAnimation(t);
        this.anim = amn;
        amn.stop();
        amn.x = x;
        amn.y = y;
        parent.addChild(amn);
        this.sprite = amn;
        Laya.timer.once(100,this,this.onLate);
    }

    onLate(){
        var bounds =  this.sprite.getBounds();
        this.setRect(bounds.x, bounds.y, bounds.width, bounds.height);
    }
    getButtonAnimation(e) {
        var t = new AnimatedNode(GameConst.animationManager.getAnimation("buttons anim"), 1 / 30, new SingleFlameSelector(e));
        t.addAction(t.totalFrames - 1, 0);
        return t;
    }

    onClick() {
        super.onClick();
        SoundsManager.instance.playSound("button");
        this.playAnim();
    };

    update(t) {
        super.update(t);
        if (this.playAnimIn > 0) {
            this.playAnimIn -= t;
            if (this.playAnimIn <= 0)
                this.playAnim();
        }
        this.anim.update(t);
    };
}

ButtonObject.prototype.playAnim = function () {
    var e = 30 * Utils.lerp(1.3, 1.6, Math.random());
    this.anim.setFrameDelay(1 / e);
    this.playAnimIn = -1;
    this.anim.gotoAndPlay(0);
};

ButtonObject.prototype.onShow = function () {
    this.playAnimIn = Utils.lerp(1 / 60, 6 / 60, Math.random());
};
ButtonObject.prototype.onHide = function () {};